﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

class Program : Form
{
    // 定义消息常量
    private const int WM_QUERYENDSESSION = 0x0011;
    private const int WM_ENDSESSION = 0x0016;

    // 定义关机和重启的标志
    private const int ENDSESSION_LOGOFF = 0x80000000; // 登出标志
    private const int ENDSESSION_SHUTDOWN = 0x00000001; // 关机标志
    private const int ENDSESSION_REBOOT = 0x00000002; // 重启标志

    [STAThread]
    static void Main()
    {
        Application.Run(new Program());
    }

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_QUERYENDSESSION) {
            // 检查是否是关机或重启
            if ((m.WParam.ToInt32() & ENDSESSION_SHUTDOWN) != 0) {
                Console.WriteLine("System is shutting down...");
            }
            else if ((m.WParam.ToInt32() & ENDSESSION_REBOOT) != 0) {
                Console.WriteLine("System is restarting...");
            }
            else {
                Console.WriteLine("Unknown session end reason.");
            }

            // 允许系统进行关机或重启
            // return new IntPtr(1); // 返回true来让系统进行关机或重启
        }
        else if (m.Msg == WM_ENDSESSION) {
            Console.WriteLine("Session has ended.");
        }

        base.WndProc(ref m);
    }
}